package com.zlf.blog.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author zlfi1
 */
@Slf4j
public class FileUtils {
    /**
     * 获取文件内容
     * @param path 文件路径
     * @return
     */
    public static String getFileContent(String path) {

        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        try {
            InputStream inputStream = new ClassPathResource(path).getInputStream();

            br = new BufferedReader(new InputStreamReader(inputStream));
            //存储对目标文件读取的内容
            String string = null;
            while ((string = br.readLine()) != null) {
                //判断读取的内容是否包含原字符串
                sb.append(string + "\n");
            }
            //关闭流，对文件进行删除等操作需先关闭文件流操作
            br.close();
        } catch (Exception e) {
            log.error("系统找不到指定文件，请核对文件存放地址");
            throw new RuntimeException("系统找不到指定文件，请核对文件存放地址");


        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    /**
     * @param file 单文件文件上传 到本地
     * @return 目的文件路径
     */
    public static Object saveFile(MultipartFile file, String path) {
        if (file.isEmpty()) {
            return "未选择文件";
        }

        //获取上传文件原来的名称
        String filename = file.getOriginalFilename();
        File temp = new File(path);
        if (!temp.exists()) {
            temp.mkdirs();
        }

        File localFile = new File(path + filename);

        try {
            file.transferTo(localFile);
            log.info("{} 上传成功", file.getOriginalFilename());
        } catch (IOException e) {
            log.error("上传失败,{}", e.getMessage());
            return "上传失败";
        }
        return localFile.getPath();
    }
}
